<template>
  <div>
    <div class="btn-box">
      <el-button type="primary" @click="onSaveData"> 保存 </el-button>
      <el-button type="primary" icon="RefreshRight" @click="refresh">
        刷新
      </el-button>
    </div>
    <div>
      <div class="form">
        <el-form
          :inline="true"
          label-suffix="："
          label-width="120px"
          size="small"
          ref="form"
        >
          <el-row>
            <el-col :span="5">
              <el-form-item
                :label="query.doctype == 1 ? '收款单号' : '付款单号'"
              >
                <el-input
                  v-model="query.doccode"
                  clearable
                  placeholder=" "
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="结算对象名称" label-width="120px">
                <div class="multiple-container">
                  <el-select
                    v-model="query.entCode"
                    placeholder="请选择结算对象"
                    style="width: 40%"
                    clearable
                    filterable
                    @change="changeOfSettle"
                    remote
                    :loading="settlementLoading"
                    :disabled="checkIsDisabled"
                  >
                    <el-option
                      v-for="item in settlementList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right">{{ item.entFullname }}</span>
                    </el-option>
                  </el-select>
                  <el-input
                    v-model="query.entFullname"
                    clearable
                    placeholder=" "
                    style="width: 60%; margin-left: 8px"
                    :disabled="true"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="收款类型">
                <el-checkbox
                  style="margin-top: 2px"
                  v-model="query.paymentType"
                  :label="query.doctype == 1 ? '收款' : '付款'"
                  size="small"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                :label="query.doctype == 1 ? '收款币种' : '付款币种'"
              >
                <el-select
                  v-model="query.currency"
                  :placeholder="
                    query.doctype == 1 ? '请选择收款币种' : '请选择付款币种'
                  "
                  style="width: 100%"
                  clearable
                  filterable
                  remote
                  :loading="currentLoading"
                  @change="currencyChangefirst"
                  :disabled="checkIsDisabled"
                >
                  <el-option
                    v-for="item in current"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left"> {{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                :label="query.doctype == 1 ? '收款金额' : '付款金额'"
              >
                <el-input
                  v-model="query.sumtotalmoney"
                  :placeholder="
                    query.doctype == 1 ? '请输入收款金额' : '请输入付款金额'
                  "
                  style="width: 100%"
                  clearable
                  @blur="jkl = false"
                  :disabled="checkIsDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                :label="query.doctype == 1 ? '收款日期' : '付款日期'"
              >
                <el-date-picker
                  v-model="query.docdate"
                  type="date"
                  clearable
                  :placeholder="
                    query.doctype == 1 ? '请选择收款日期' : '请选择付款日期'
                  "
                  :size="'small'"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  :disabled="checkIsDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="业务员">
                <el-select
                  v-model="query.salesName"
                  placeholder="请选择业务员"
                  style="width: 100%"
                  clearable
                  filterable
                  remote
                  :remote-method="getSalesman"
                  @change="salesNameFill"
                  :loading="salesmanLoading"
                  :disabled="checkIsDisabled"
                >
                  <el-option
                    v-for="item in salesman"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="销账币种">
                <el-select
                  v-model="query.feeCurrency"
                  placeholder="请选择销账币种"
                  style="width: 100%"
                  clearable
                  filterable
                  remote
                  @change="currencyChange"
                  :disabled="checkIsDisabled"
                >
                  <el-option
                    v-for="item in current"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left"> {{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="汇率">
                <el-input
                  v-model="query.exchangeRate"
                  placeholder="请输入汇率"
                  clearable
                  style="width: 100%"
                  @blur="jkl = false"
                  :disabled="checkIsDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="销账金额">
                <el-input
                  v-model="query.canverificationMoney"
                  placeholder="请输入销账金额"
                  clearable
                  style="width: 100%"
                  @blur="onBlur"
                  :disabled="checkIsDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="已销金额">
                <el-input
                  v-model="query.sumverificationMoney"
                  clearable
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="未销金额">
                <el-input
                  v-model="query.unVerificationMoney"
                  clearable
                  placeholder=" "
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="审核状态">
                <el-select
                  v-model="query.checkStatus"
                  placeholder="请输入审核状态"
                  style="width: 100%"
                  clearable
                  filterable
                  :disabled="true"
                >
                  <el-option
                    v-for="item in status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="银行账号">
                <div class="multiple-container">
                  <el-select
                    v-model="query.bankAccountName"
                    placeholder="请选择银行账号"
                    filterable
                    remote
                    :remote-method="getBankAccount"
                    @change="onClickBank"
                    :loading="bankAccountLoding"
                    :disabled="checkIsDisabled"
                  >
                    <el-option
                      v-for="(item, index) in bankAccountList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                      <span style="float: left">
                        {{ item.bankAccount + "-" + item.accountName }}</span
                      >
                    </el-option>
                  </el-select>
                  <el-input
                    v-model="query.bankAccount"
                    clearable
                    placeholder=" "
                    :disabled="true"
                    style="width: 60%; margin-left: 8px"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="录入人">
                <el-input
                  v-model="query.createBy"
                  clearable
                  placeholder=" "
                  style="width: 100%"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="录入日期">
                <el-date-picker
                  v-model="query.createTime"
                  type="datetime"
                  placeholder=" "
                  :size="'small'"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="摘要">
                <el-input
                  v-model="query.memo"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入摘要"
                  @blur="jkl = false"
                  :disabled="checkIsDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 因为使用计算属性要有个输出的地方 -->
    <span style="display: none">{{ unVerificationMoney }}</span>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import request from "@/public/request";
import { ElMessage, ElMessageBox } from "element-plus";
import bus from "@/utils/vueBus";
import dayjs from "dayjs";
import vueBus from "@/utils/vueBus";
export default defineComponent({
  data() {
    return {
      //表单默认值
      query: {
        doctype: null,
        paymentType: true,
        sumtotalmoney: undefined,
        canverificationMoney: undefined,
        sumverificationMoney: undefined,
        unVerificationMoney: undefined,
        entId: "",
        currency: "",
        feeCurrency: "",
        exchangeRate: undefined,
        checkStatus: 0,
        createBy: localStorage.getItem("userName"),
        createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        salesId: null,
        salesName: null,
        entFullname: "",
        docdate: dayjs().format("YYYY-MM-DD"),
        bankAccount: "",
        bankAccountName: "",
        bankName: "",
      },
      //结算对象所需数据
      settlementList: [],
      settlementLoading: false,
      //币种类型所需数据
      currentLoading: false,
      current: [],
      //业务员所需数据
      salesmanLoading: false,
      salesman: [],
      exchangeArr: [],
      bankAccountList: [],
      bankAccountLoding: false,
      // 审核状态
      status: [
        {
          label: "草拟",
          value: 0,
        },
        {
          label: "提交审核",
          value: 1,
        },
        {
          label: "审核通过",
          value: 2,
        },
        {
          label: "驳回",
          value: -1,
        },
      ],
      jkl: true,
    };
  },
  watch: {
    "query.feeCurrency"(newval) {
      this.exchangeArr.forEach((element) => {
        if (element.currency === newval) {
          this.query.exchangeRate = element.exchangeRate;
        }
      });
    },
    //监听收款金额的值，来让收款金额和销账金额数值保持一致
    "query.sumtotalmoney"(newval) {
      if (this.query.feeCurrency === this.query.currency) {
        if (newval >= this.query.sumverificationMoney) {
          this.query.canverificationMoney = newval;
        } else {
          this.query.canverificationMoney = this.query.sumverificationMoney;
        }
      } else {
        var a = 0;
        var b = 0;
        this.exchangeArr.forEach((element) => {
          if (element.currency === this.query.feeCurrency) {
            a = element.exchangeRate;
          }
          if (element.currency === this.query.currency) {
            b = element.exchangeRate;
          }
        });
        let num = (b / a) * newval;
        if (num >= this.query.sumverificationMoney) {
          this.query.canverificationMoney = num;
        } else {
          this.query.canverificationMoney = this.query.sumverificationMoney;
        }
      }
    },
    
  },
  computed: {
    //通过计算属性来计算未销金额的值
    unVerificationMoney() {
      if (
        this.query.canverificationMoney !== undefined &&
        this.query.sumverificationMoney !== undefined
      ) {
        return (this.query.unVerificationMoney =
          this.query.canverificationMoney - this.query.sumverificationMoney);
      }
    },
    // 审核状态判断是否可编辑
    checkIsDisabled(){
      if(this.query.checkStatus == 1 ||  this.query.checkStatus == 2){
        return true
      }else{
        return false
      }
    }
  },
  mounted() {
    this.getPageData();
    this.getBusDetail();
    this.getCurrentData();
    //this.getSalesman();
    //接收cashadd组件传来的值，并赋予给表单的已销金额的值
    bus.on("getVerificationMoney", (val) => {
      if (this.query.sumverificationMoney === undefined) {
        this.query.sumverificationMoney = val;
      }
      // this.query.sumverificationMoney = val;
    });
    //判断为收还是付
    bus.on("doctype", (val) => {
      this.query.doctype = val;
      this.getexchange();
    });
    //表格的销账回显到表单
    vueBus.on("selectedOne", (val) => {
      if (this.query.canverificationMoney === undefined) {
        this.query.canverificationMoney = val;
      }
    });
  },
  methods: {
    //获取汇率
    getexchange() {
      this.$http
        .get("/api/base/exchangerate/query", {
          IsIncome: this.query.doctype,
        })
        .then((res) => {
          this.exchangeArr = res.content;
        });
    },
    //根据路由分多钟场景跳入该组件获取页面数据
    async getPageData() {
      //判断是否是从应收应付对账页面的销账中跳转
      if (this.$route.query.currency) {
        //通过父组件的selectedIds查到是哪个账单并将数据回显到表单中
        const selectedIds = JSON.parse(this.$route.query.selectedIds);
        this.$http
          .post(`/api/docBalance/getFeeListByBalanceIds?feeStatus=0`, {
            idArray: selectedIds,
          })
          .then((res) => {
            this.query = res[0];
            this.query.docdate = dayjs().format("YYYY-MM-DD");
            this.query.checkStatus = 0;
            this.query.doccode = "";
            if (res.length !== 0 && res.length >= 2) {
              const rows = res.filter(
                (item) => item.currency == this.$route.query.currency
              );
              let price = rows.reduce(
                (sum, e) => sum + Number(e.getTotalmoney || 0),
                0
              );
              this.query.sumtotalmoney = price;
              this.query.canverificationMoney = price;
              this.query.sumverificationMoney = price;
              this.query.unVerificationMoney = 0;
            } else {
              this.query.sumtotalmoney = res[0].getUnVerificationMoney;
              this.query.canverificationMoney = res[0].getUnVerificationMoney;
              this.query.sumverificationMoney = res[0].getUnVerificationMoney;
              this.query.unVerificationMoney = 0;
            }
            this.query.feeCurrency = this.$route.query.currency;
            this.query.doctype = this.$route.query.DocType;
            this.query.paymentType = true;
          });
        this.query.createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
      }
      if (this.$route.query.id) {
        vueBus.on("dataForm", (searchData) => {
          this.query = searchData.data;
          this.query.paymentType = true;
        });
      }
    },
    // 选择收款/付款币种，并会刷新页面
    currencyChangefirst(){
      this.jkl = false;
      this.$emit("clearTableData");
      this.query.sumtotalmoney = 0;
      this.query.bankAccount = "";
      this.query.bankAccountName = "";
      this.query.bankName = "";
      this.query.feeCurrency = this.query.currency;
    },
    //选择币种，并会刷新页面
    currencyChange() {
      this.jkl = false;
      this.$emit("clearTableData");
      this.query.sumtotalmoney = 0;
      this.query.bankAccount = "";
      this.query.bankAccountName = "";
      this.query.bankName = "";
    },
    //获取结算对象的数据
    async getBusDetail() {
      this.settlementLoading = true;
      let res = await this.$http.get("/api/buenterprise/dropdownlist");
      res.forEach((item) => {
        item.label = item.entCode;
        item.value = item.id;
      });
      this.settlementList = res;
      this.settlementLoading = false;
    },
    // 获取币种类型
    async getCurrentData() {
      this.currentLoading = true;
      let res = await this.$http.get("/api/base/currency/dropdownlist",{

      });
      this.current = res.map((item) => {
        return {
          label: item.currencyCode + "|" + item.currencyName,
          value: item.currencyCode,
        };
      });
      this.currentLoading = false;
    },
    // 获取业务员
    async getSalesman(val) {
      this.salesmanLoading = true;
      let res = await this.$http.get("/api/user/userList", {
        keyword: val,
      });
      res.forEach((item) => {
        item.label = item.nickName;
        item.value = item.id;
      });
      this.salesman = res;
      this.salesmanLoading = false;
    },
    //选择银行账户
    async getBankAccount() {
      
      if (this.query.feeCurrency === "") {
        return;
      }
      this.bankAccountLoding = true;
      this.bankAccountList = [];
      let res = await request.get("/api/companybank/queryByCurrency", {
        Currency: this.query.feeCurrency
      });
      res.forEach((item) => {
        item.label = item.accountName;
        item.value = item.accountName;
      });
      this.bankAccountList = res;
      this.bankAccountLoding = false;
    },
    //判断销账的值是否小于已销的值
    onBlur() {
      if (this.query.canverificationMoney < this.query.sumverificationMoney) {
        this.query.canverificationMoney = this.query.sumverificationMoney;
        this.jkl = false;
      }
    },
    //结算对象的值
    changeOfSettle(val) {
      if (val) {
        for (const iterator of this.settlementList) {
          if (iterator.id == val) {
            this.query.entFullname = iterator.entFullname;
            this.query.entCode = iterator.entCode;
            this.query.entId = iterator.id;
          }
        }
        this.jkl = false;
      } else {
        this.query.entFullname = "";
        this.query.entCode = "";
        this.jkl = false;
      }
      this.$emit("clearTableData");
      this.query.sumtotalmoney = 0;
    },
    // 业务员名称
    salesNameFill(val) {
      if (val) {
        for (const iterator of this.salesman) {
          if (iterator.id == val) {
            this.query.salesName = iterator.label;
            this.query.salesId = val;
          }
        }
        this.jkl = false;
      } else {
        this.query.salesName = null;
        this.query.salesId = null;
        this.jkl = false;
      }
    },
    //获取选中的银行账户
    onClickBank(val) {
      this.bankAccountList.forEach((item) => {
        if (item.label === val) {
          this.query.bankAccount = item.bankAccount;
          this.query.bankAccountName = item.accountName;
          this.query.bankName = item.bankName;
          this.jkl = false;
        }
      });
    },
    //保存
    onSaveData() {
      if (this.$route.query.currency) {
        this.query.isDZ = true;
      }
      this.$emit("saveData", this.query);
      this.jkl = true;
    },
    // 刷新
    refresh() {
      if (this.$route.query.iscash && this.jkl) {
        this.$emit("onEarch");
        ElMessage.success("刷新成功");
      } else {
        if (this.jkl) {
          ElMessage.success("刷新成功");
          return;
        }
        ElMessageBox.confirm("您编辑的数据还未保存，确认刷新吗？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            if (this.$route.query.iscash) {
              this.$emit("onEarch");
              ElMessage.success("刷新成功");
              this.jkl = true;
            } else if (this.$route.query.currency) {
              this.getPageData();
              ElMessage.success("刷新成功");
              this.jkl = true;
            } else {
              this.query = {
                doctype: 1,
                paymentType: true,
                createBy: localStorage.getItem("userName"),
                checkStatus: 0,
                createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                docdate: dayjs().format("YYYY-MM-DD"),
              };
              ElMessage.success("刷新成功");
            }
          })
          .catch(() => {});
      }
    },
  },
});
</script>

<style lang="scss" scoped>
:deep(.el-checkbox__inner) {
  width: 20px !important;
  height: 20px !important;
}
:deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after) {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
.multiple-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.btn-box {
  margin-bottom: 8px;
}

:deep(.el-form-item--small .el-form-item__label) {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.el-input--suffix .el-input__inner) {
  padding-right: 4px;
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
  margin-right: 0;
}

:deep(.el-select__wrapper.is-disabled span) {
  color: #a8abb2 !important;
}

:deep(.el-form-item--small.el-form-item) {
  margin-bottom: 8px;
}
</style>
